#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>

#include "dbcom.h"
#include "dbfunc.h"


int DbsEMP_SEL(int thrd_index, emp_t *p_emp)
{
    DEFAULT_DEFINITION;

    sprintf(ThrdConn.sql, "select no,upd_ts,name,duty,age,salary from emp where no=%.lf", p_emp->no);
    if(mysql_query(ThrdConn.sock, ThrdConn.sql) ||
       !(ThrdConn.res=mysql_store_result(ThrdConn.sock)))
        ReturnErr;
    if(!(ThrdConn.row=mysql_fetch_row(ThrdConn.res)))
    {
        CheckErr;
        if(errcode==0)  errcode=DB_NOTFOUND;
        return(errcode);
    }

    p_emp->no=atof(ThrdConn.row[0]);
    strcpy(p_emp->upd_ts, ThrdConn.row[1]);
    strcpy(p_emp->name, ThrdConn.row[2]);
    strcpy(p_emp->duty, ThrdConn.row[3]);
    p_emp->age=atoi(ThrdConn.row[4]);
    p_emp->salary=atof(ThrdConn.row[5]);

    mysql_free_result(ThrdConn.res);

    return(DB_OK);
}


int DbsEMP_CUR(int thrd_index, emp_t *a_emp, int *query_qt)
{
    DEFAULT_DEFINITION;

    sprintf(ThrdConn.sql, "select no,name,age from emp where age<%d order by no", a_emp[0].age);
    if(mysql_query(ThrdConn.sock, ThrdConn.sql) ||
       !(ThrdConn.res=mysql_use_result(ThrdConn.sock)))
        ReturnErr;

    *query_qt=0;
    while(ThrdConn.row=mysql_fetch_row(ThrdConn.res)) 
    {
        a_emp[*query_qt].no=atof(ThrdConn.row[0]);
        strcpy(a_emp[*query_qt].name, ThrdConn.row[1]);
        a_emp[*query_qt].age=atoi(ThrdConn.row[2]);
        (*query_qt)++;
    }
    CheckErr;
    mysql_free_result(ThrdConn.res);
    return(errcode);
}


int DbsRESUME_INS(int thrd_index, resume_t *p_resume)
{
    DEFAULT_DEFINITION;

    sprintf(ThrdConn.sql, "insert into resume values(%.0lf,'%s')", p_resume->no, p_resume->resume);
    if(mysql_query(ThrdConn.sock, ThrdConn.sql))
        ReturnErr;

    return(DB_OK);
}


int DbsRESUME_SEL(int thrd_index, resume_t *p_resume)
{
    DEFAULT_DEFINITION;

    sprintf(ThrdConn.sql, "select resume from resume where no=%.lf", p_resume->no);
    if(mysql_query(ThrdConn.sock, ThrdConn.sql) ||
       !(ThrdConn.res=mysql_store_result(ThrdConn.sock)))
        ReturnErr;
    if(!(ThrdConn.row=mysql_fetch_row(ThrdConn.res)))
    {
        CheckErr;
        if(errcode==0)  errcode=DB_NOTFOUND;
        return(errcode);
    }

    strcpy(p_resume->resume, ThrdConn.row[0]);

    mysql_free_result(ThrdConn.res);

    return(DB_OK);
}
